<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace App\Views\Lib;

use Sun\Html;
use Sun\Html\Form;
use App\Models;
use App\Models\DB;

class Edition extends Main {
    private $edit;
    public function __construct() {
        parent::__construct();
        $this->edit = new Models\Edition();
        $this->data_scene = 'Body';
    }


    public function AltScene() {
        $this->cond['Alt'] = 1;
        $query = "SELECT field_id, value FROM dict_rel, dictionary
            WHERE dict_rel.rec_id = dictionary.rec_id AND edit_id = '{$this->data['edit_id']}'";
        $fields = $this->edit->db->SafeQuery($query)->fetchAll(DB::FETCH_ASSOC);

        if (empty($this->data['type_id'])) {
            $query = "SELECT type_id FROM edition WHERE edit_id = '{$this->data['edit_id']}'";
            $res = $this->edit->db->SafeQuery($query)->fetch(DB::FETCH_NUM);
            $this->data['type_id'] = $res[0];
        }

        $fid = $fields[0]['field_id'];
        $fval = $fields[0]['value'];

        for ($i = 1; $i < count($fields); ++$i) {
            $fid .= ",".$fields[$i]['field_id'];
            $fval .= "[^&]".$fields[$i]['value'];
        }
        $this->data['fid'] = $fid;
        $this->data['fval'] = $fval;

        $this->IncludeScene("AltBody");
    }

    public function AcceptAddScene() {
        echo '<div class="Message">Издание добавлено</div>';
    }

    public function EmptyFailScene() {
        echo '<div class="Warning">Должно быть заполнено хотя бы 1 поле</div>';
    }

    public function FormFieldRowScene() {
        echo $this->FormFieldRow(
            $this->data['num_row'],
            $this->data['field_id']
        )->ToJSON();
    }

    // управление изданиями
    public function SearchResultScene() {
        $edits = $this->edit->SimlpeSearch($this->data['EditType'], $this->data['SearchVal']);
        $rows = array();
        foreach ($edits as $e) {
            $rows[] = array($this->edit->GetEditBrief($e[0]));
        }
        $table = new Html\QueryTable($rows, array("Описание"));
        $table->First()->id = "SearchTable";
        $table->SetAttribute('class', $table->Attribute('class').' EditionList');

        $rows = $table->First()->Childs();
        $rows[0]->AddFirst(new Html\TData())
                ->Added()->Add(new Html\Text("№"));
        $rows[0]->AddData()->AddData();
        for ($i = 1; $i < count($rows); ++$i){
            $rows[$i]->SetAttribute("data-edit", $edits[$i - 1][0])
                    ->AddFirst(new Html\TData())
                    ->Added()->SetAttribute("style", "width: 4px;")
                    ->Add(new Html\Text($i));
            $rows[$i]->AddData()
                    ->Added()->SetAttribute("style", "width: 4px;")
                    ->Add(new Html\A(array(
                        'href' => 'Добавить')))
                    ->Added()->Add(new Html\Img(array(
                        'src' => "pub/media/images/add_16.png",
                        'alt' => "Добавить",
                        'class' => "NoneBorder")));
            $rows[$i]->AddData()
                    ->Added()->SetAttribute("style", "width: 4px;")
                    ->Add(new Html\A(array('href' => "?u=Lib&p=Lib\\\\Edition/Alt&edit_id="
                            . $edits[$i - 1][0],
                        'target' => '_blank')))
                    ->Added()->Add(new Html\Img(array(
                        'src' => "pub/media/images/edit_16.png",
                        'alt' => "Изменить",
                        'class' => "NoneBorder")));
        }
        echo "{ content: {$table->ToJSON()} }";
    }



    // список полей для заполнения
    public function FieldList() {
        if (!empty($this->data['fid']) || !empty($this->cond['Err'])) {
            $curr_f = explode(",", $this->data['fid']);
            $curr_v = explode("[^&]", $this->data['fval']);
        }
        if (empty($this->data['type_id']))
            $this->data['type_id'] = $this->edit->GetFirstEditType();
        $type_f = $this->edit->GetEditTypeFields($this->data['type_id']);

        $values = array();
        if (empty($curr_f)) {
            $fields = $type_f;
        } else {
            $fields = array();

            $check = function($id, $fields) {
                foreach ($fields as $f) {
                    if ($id == $f) return false;
                }
                return true;
            };
            for ($i = 0; $i < count($curr_f); ++$i) {
                if (!empty($curr_v[$i])) {
                    $fields[] = $curr_f[$i];
                    $values[] = $curr_v[$i];
                }
            }
            if (empty($this->cond['Alt'])) {
                foreach ($type_f as $f) {
                    if ($check($f, $fields)) {
                        $fields[] = $f;
                        $values[] = "";
                    }
                }
            }
        }

        $table = new Html\Table(array(
            'cellspacing' => 0,
            'class' => "RowDiv",
            'id' => "FieldList"
        ));

        $body = $table->AddBody()->Added();
        $ids = array();
        $tyeps = array();
        for ($i = 0; $i < count($fields); ++$i) {
            $row = $this->FormFieldRow($i, $fields[$i], $values);
            $body->Add($row);

            $ids[] = $fields[$i];
        }

        $set = new Html\HtmlSet();
        $set->Add($table);
        $set->Add(new Form\Input("hidden", array(
            'id' => "FieldSet",
            'value' => implode(",", $ids),
            'data-count' => $i
        )));
        return $set;
    }

    public function AllFieldList() {
        $fields = $this->edit->db->Table("field")->fetchAll(DB::FETCH_ASSOC);
        $select = new Form\Select(array('class' => 'ListBox', 'size' => '15'));
        $select->id = 'FieldListBox';

        foreach ($fields as $field) {
            $select->AddOption($field['field_id'], $field['name'])
                ->Added()->id = 'Opt'.$field['field_id'];
        }
        $select->First()->selected = 'selected';
        return $select;
    }

    public function EditTypes($id = "type_id", $all = false) {
        $types = $this->edit->GetEditionTypes();
        $select  = new Form\Select(array(
            'id' => $id,
            'class' => "SelectBox"));
        if ($all) $select->AddOption(-1, "Все");
        foreach ($types as $type) {
            $select->AddOption($type['type_id'], $type['name']);
            if (@$this->data[$id] == $type['type_id'])
                $select->Added()->selected = "selected";
        }
        if (empty($this->data[$id])) {
            $select->First()->selected = "selected";
            $this->data[$id] = $select->First()->value;
        }
        return $select;
    }


    public function ItemBrief() {
        return $this->edit->GetEditInventoryBrief($this->data['edit_id']);
    }

    public function EditBrief() {
        $edition = new Models\Edition();

        $edits = $edition->db->Table("edition", "edit_id")->fetchAll(DB::FETCH_NUM);
        $rows = array();
        foreach ($edits as $e) {
            $rows[] = array($edition->GetEditBrief($e[0]));
        }

        $table = new Html\QueryTable($rows, Array("Описание"));
        $table->SetAttribute("id", "EditList");

        $body = $table->First();
        $i = 0;
        foreach ($body->Childs() as $row) {
            if ($i > 0) {
                $id = $edits[$i - 1][0];
                $row->SetAttribute("data-id", $id)
                    ->AddFirst(new Html\Text("<td>{$i}</td>"))
                    ->Add(new Html\Text("<td class=\"AlignCenter\"><a data-id=\"{$id}\" href=\"{$id}\">
                        <img class=\"EditImage\" src=\"pub/media/images/home_16.png\" alt=\"Alt\"/></a></td>"));
            } else {
                $row->AddFirst(new Html\Text("<td>№</td>"))
                    ->Add(new Html\Text("<td class=\"AlignCenter\"></td>"));
            }
            ++$i;
        }

        $src = <<<SCRIPT
   function AltEdit() {
       jsun.swap['Action'] = "AltEdit";
       //jsun.page.my("u=Lib&p=Lib\\\\Edition/EditList&Page=" + jsun.swap["EditList"]["Page"]);
       var param = "u=Lib&p=Lib\\\\Edition/Alt&edit_id=" + this.getAttribute("data-id");
       jsun.page.request(param);
   }

   var dom = jsun.dom;
   var body = dom.by_id("EditList").firstChild;
   for (var i = 1; i < body.childNodes.length; ++i) {
       dom.mix(body.childNodes[i].lastChild.firstChild).event({ onclick: AltEdit });
   }
SCRIPT;
        $script = new Html\Script($src, array('id' => "AltEditAScript"));
        $table->Add($script);
        return $table->ToHtml();
    }

    public function FormFieldRow($i, $id, $values = null, $data = null) {
        $query = "SELECT field.name \"name\", sense FROM field, field_type
            WHERE field_type.type_id = field.type_id AND field_id = '{$id}'";
        $field = $this->edit->db->SafeQuery($query)->fetch(DB::FETCH_ASSOC);;

        $row = new Html\TRow(array('id' => "Row_".$i, 'data-i' => $i));
        $row->AddData()->Added()
            ->SetAttributes(array('style' => "max-width: 200px;"))
            ->Add(new Html\Text($field['name']));
        $row->AddData()->Added()
            ->Add(new Form\TextArea(@$values[$i], array(
                'class' => "TextArea", 'id' => "F_".$i,
                'cols' => "30", 'rows' =>"2"
            )));

        if ($field['sense'] != "STR")
            $row->Added()->Add(new Html\Div())->Added()
            ->Add(new Form\Input("file", array('class' => "FileInput",
                'id' => "File".$i, 'name' => "File".$i)))
            ->Add(new Form\Input("button", array(
                'value' => "Загрузить", 'id' => "Load_".$i)))
            ->Add(new Form\Input("hidden", array(
                'id' => "FileId_".$i)));

        $row->AddData()->Added()
            ->Add(new Html\HtmlContainer("a", array(
                'href' => "Словарь", 'id' => "A_".$i, 'data-i' => $i
            )))->Added()->Add(new Html\Text("Словарь"));
        if ($i % 2 == 0) $row->SetAttribute("class", "Odd");
        $u = $row->ToJSON();
        return $row;
    }


}
